<template>
    <div class="app-container">
      <div class="container_box">
        <el-row>
          <el-col :xs="24" :sm="24" :md="24" :lg="14" :xl="12">
            <el-form ref="form" :model="form" :rules="rules" label-width="110px">
              <el-row>
                <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                  <el-form-item label="報價編碼" prop="quoteCode">
                    <el-input
                      disabled
                      v-model="form.quoteCode"
                      placeholder="請輸入標題"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                  <el-form-item label="標題" prop="quoteTitle">
                    <el-input
                      v-model="form.quoteTitle"
                      placeholder="請輸入標題"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                  <el-form-item label="報價人" prop="quoterName">
                    <el-input
                      disabled
                      v-model="form.quoterName"
                      placeholder="請輸入報價人"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col
                  :xs="24"
                  :sm="12"
                  :md="12"
                  :lg="12"
                  :xl="12"
                  v-if="form.reservationId!=null"
                >
                  <el-form-item label="預約編碼" prop="reservationCode">
                    <el-input
                      disabled
                      v-model="form.reservationCode"
                      placeholder="請輸入預約編碼"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col
                  :xs="24"
                  :sm="12"
                  :md="12"
                  :lg="12"
                  :xl="12"
                  v-if="form.reservationId==null"
                >
                  <el-form-item label="客戶編碼" prop="customerCode">
                    <el-input
                      disabled
                      v-model="form.customerCode"
                      placeholder="請選擇客戶編碼"
                    >
                      <el-button
                        slot="append"
                        @click="open_dialog_customer"
                        icon="el-icon-search"
                      ></el-button>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col
                v-if="form.reservationId!=null"
                  :xs="24"
                  :sm="12"
                  :md="12"
                  :lg="12"
                  :xl="12"
                >
                  <el-form-item label="客戶編碼" prop="customerCode">
                    <el-input
                      disabled
                      v-model="form.customerCode"
                      placeholder="請選擇客戶編碼"
                    >
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                  <el-form-item label="客戶名稱" prop="customerName">
                    <el-input
                      disabled
                      v-model="form.customerName"
                      placeholder="請選擇客戶名稱"
                    >
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                  <el-form-item label="入賬銀行賬號" prop="inBankNo">
                    <el-input
                      disabled
                      v-model="form.inBankNo"
                      placeholder="請選擇賬銀行賬號"
                    >
                      <el-button
                        slot="append"
                        @click="open_dialog"
                        icon="el-icon-search"
                      ></el-button>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                  <el-form-item label="入賬銀行名稱" prop="inBankName">
                    <el-input
                      disabled
                      v-model="form.inBankName"
                      placeholder="請輸入入賬銀行名稱"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                  <el-form-item label="有效天數" prop="validDays">
                    <el-input
                      v-model="form.validDays"
                      placeholder="請輸入有效天數"
                    >
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                  <el-form-item label="稅率" prop="taxRate">
                    <el-input
                      maxlength="4"
                      placeholder="請輸入稅率（0-1）"
                      @change="taxRate_change"
                      oninput="value=value.replace(/^0[0-9]|^[2-9]|^1[0-9]|^1\.|[^\d.]/g,'')"
                      v-model="form.taxRate"
                    />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                  <el-form-item label="備註" prop="remark">
                    <el-input v-model="form.remark" placeholder="請輸入備註" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <!--  -->
            <el-divider content-position="center">報價單明細</el-divider>
            <el-row>
              <el-col :xs="24" :sm="24" :md="24" :lg="24">
                <el-button
                  type="primary"
                  icon="el-icon-plus"
                  size="mini"
                  @click="add"
                  >添加</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="del"
                  >删除</el-button
                >
  
                <el-table
                  style="width: 100%"
                  :data="bizInvoiceItemList"
                  :row-class-name="rowItemIndex"
                  :row-key="
                    (row) => {
                      return row.index;
                    }
                  "
                  @selection-change="SelectionChange"
                  ref="bizCustomerReservationItem"
                >
                  <el-table-column type="selection" width="50" align="center" />
                  <el-table-column
                    label="序號"
                    align="center"
                    prop="index"
                    width="50"
                  />
                  <el-table-column label="報價事項" align="center" prop="itemKey">
                    <template slot-scope="scope">
                      <el-select
                        v-model="scope.row.itemKey"
                        placeholder="請選擇報價事項"
                        clearable
                      >
                        <el-option
                          v-for="dict in dict.type.business_scope"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        />
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="報價金額"
                    align="center"
                    prop="itemAmount"
                  >
                    <template slot-scope="scope">
                      <el-input
                        min="0"
                        @change="amountSum(scope.row)"
                        v-model="scope.row.itemAmount"
                        placeholder="請輸入報價金額"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column label="備註" prop="remark">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.remark"
                        placeholder="請輸入備註"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column label="稅金" align="center" prop="taxAmount">
                    <template slot-scope="scope">
                      <span v-if="scope.row.itemAmount">{{
                        scope.row.taxAmount
                      }}</span>
                      <span v-else>0</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="報價含稅金額"
                    align="center"
                    prop="itemTaxAmount"
                  >
                    <template slot-scope="scope">
                      <span v-if="scope.row.itemAmount">{{
                        scope.row.itemTaxAmount
                      }}</span>
                      <span v-else>0</span>
                    </template>
                  </el-table-column>
                </el-table>
              </el-col>
            </el-row>
  
            <div style="text-align: center; margin-top: 16px">
              <el-button type="primary" @click="submitForm('20')"
                >提 交</el-button
              >
              <el-button type="primary" @click="submitForm('10')"
                >保 存</el-button
              >
              <el-button @click="cancel">取 消</el-button>
            </div>
          </el-col>
        </el-row>
  
        <!-- 添加或修改客户 -->
  
        <el-dialog
          v-if="dialog_if"
          :title="title"
          :visible.sync="open"
          destroy-on-close
          :close-on-click-modal="false"
          width="600px"
          append-to-body
        >
          <!-- 单选表格 -->
          <el-table
            v-loading="loading"
            :data="userList"
            class="signType"
            max-height="500"
            ref="multipleTable"
            @selection-change="handleSelectionChange"
            @select="selectTable"
            :row-key="
              (row) => {
                return row.id;
              }
            "
          >
            <el-table-column
              type="selection"
              width="50"
              align="center"
              :reserve-selection="true"
            />
            <el-table-column label="賬戶分類" align="center" prop="bankType">
              <template slot-scope="scope">
                <dict-tag
                  :options="dict.type.bank_type"
                  :value="scope.row.bankType"
                />
              </template>
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              label="賬戶名稱"
              align="center"
              prop="accountName"
            />
            <el-table-column
              show-overflow-tooltip
              label="銀行名稱"
              align="center"
              prop="bankName"
            />
            <el-table-column
              show-overflow-tooltip
              label="銀行賬號"
              align="center"
              prop="bankNo"
            />
          </el-table>
          <div class="dialog-footer" style="text-align: center">
            <el-button @click="cancel_bank">取 消</el-button>
            <el-button type="primary" @click="choose_bank">確 定</el-button>
          </div>
        </el-dialog>
  
        <!-- 選擇客戶 -->
  
        <el-dialog
          v-if="dialog_if_customer"
          :visible.sync="open_customer"
          destroy-on-close
          :close-on-click-modal="false"
          width="600px"
          append-to-body
        >
          <!-- 单选表格 -->
          <el-table
            v-loading="loading"
            :data="userList_customer"
            class="signType"
            max-height="500"
            ref="multipleTable_customer"
            @selection-change="handleSelectionChange_customer"
            @select="selectTable_customer"
            :row-key="
              (row) => {
                return row.id;
              }
            "
          >
            <el-table-column
              type="selection"
              width="50"
              align="center"
              :reserve-selection="true"
            />
            <el-table-column label="客戶編碼" align="center" prop="customerCode">
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              label="客戶名稱"
              align="center"
              prop="customerName"
            />
            <el-table-column
              show-overflow-tooltip
              label="郵箱"
              align="center"
              prop="email"
            />
            <el-table-column
              show-overflow-tooltip
              label="性別"
              width="60"
              align="center"
              prop="sex"
            >
              <template slot-scope="scope">
                <dict-tag
                  :options="dict.type.sys_user_sex"
                  :value="scope.row.sex"
                />
              </template>
            </el-table-column>
          </el-table>
          <div class="dialog-footer" style="text-align: center">
            <el-button @click="cancel_customer_customer">取 消</el-button>
            <el-button type="primary" @click="choose_customer_customer"
              >確 定</el-button
            >
          </div>
        </el-dialog>
      </div>
    </div>
  </template>
      
      <script>
  import {
    listQuote,
    getQuote,
    delQuote,
    addQuote,
    updateQuote,
  } from "@/api/biz/quote";
  import {
    listBank,
    getBank,
    delBank,
    addBank,
    updateBank,
  } from "@/api/biz/bank";
  import {
    listCustomer,
    getCustomer,
    delCustomer,
    addCustomer,
    updateCustomer,
  } from "@/api/biz/customer";
  import {
    listReservation,
    getReservation,
    delReservation,
    addReservation,
    putReservationComplete,
    updateReservation,
  } from "@/api/biz/reservation";
  export default {
    name: "QuoteEdit",
    dicts: [
      "customer_type",
      "customer_tag",
      "customer_source",
      "industry_type",
      "cart_type",
      "sys_user_sex",
      "customer_level",
      "bank_type",
      "sys_yes_no",
      "sys_normal_disable",
      "quote_source",
      "quote_status",
      "business_scope",
    ],
    data() {
      return {
        // 表单參數
        form: {
          quoterName: this.$store.state.user.nickName,
          validDays: 30,
          taxRate: 0,
        },
  
        // 表单校验
        rules: {
          email: [
            { required: true, message: "郵箱地址不能為空", trigger: "blur" },
            {
              type: "email",
              message: "請輸入正確的郵箱地址",
              trigger: ["blur", "change"],
            },
          ],
          // inBankNo: [
          //   { required: true, message: "客戶名稱不能為空", trigger: "blur" },
          // ],
        },
        title: "",
        // 是否顯示弹出层
        loading: false,
        open: false,
        dialog_if: false,
        multipleSelection: [],
        select_customer: {},
        userList: [],
        // 查询參數
        queryParams: {
          pageNum: 1,
          pageSize: 9999,
          orderByColumn: "update_time",
          isAsc: "desc",
        },
        // 報價單明細表格數据
        bizInvoiceItemList: [],
        checkedList: [],
        //------------------------
        open_customer: false,
        dialog_if_customer: false,
        multipleSelection_customer: [],
        select_customer_customer: {},
        userList_customer: [],
      };
    },
    created() {
      if (this.$route.query.id) {
        console.log(this.$route.query);
        this.get_detail(this.$route.query.id);
      }
    },
    activated() {
      if (this.$route.query.id) {
        this.get_detail(this.$route.query.id);
      }
    },
    methods: {
      get_detail(id) {
        getQuote(id).then((response) => {
          // this.form = response.data;
          // this.open = true;
          // this.title = "修改報價單";
          this.form = response.data;
  
          // this.form.reservationCode = response.data.reservationCode;
          // this.form.reservationId = response.data.id;
          // this.form.customerCode = response.data.customerCode;
          // this.select_customer_customer.id = response.data.customerId;
          // this.form.customerId = response.data.customerId;
          // this.form.customerName = response.data.customerName;
          // this.form.quoteSource = "10";
          this.bizInvoiceItemList = response.data.bizQuoteItemList;
  
          //     response.data.bizCustomerReservationItemList.map((item) => {
          //       let obj = {};
          //       obj.itemKey = item.reservationItem;
          //       obj.itemAmount = "";
          //       obj.taxAmount = "";
          //       obj.itemTaxAmount = "";
          //       obj.taxRate = this.form.taxRate;
          //       obj.quantity = 1;
          //       obj.uint = "個";
          //       obj.unitPrice = "";
          //       obj.remark = item.remark;
          //       this.bizInvoiceItemList.push(obj);
          //     });
        });
      },
  
      getReservation(id) {
        getReservation(id).then((response) => {
          console.log(response.data);
          this.form.reservationCode = response.data.reservationCode;
          this.form.reservationId = response.data.id;
          this.form.customerCode = response.data.customerCode;
          this.select_customer_customer.id = response.data.customerId;
          this.form.customerId = response.data.customerId;
          this.form.customerName = response.data.customerName;
          this.form.quoteSource = "10";
          this.bizInvoiceItemList = [];
  
          response.data.bizCustomerReservationItemList.map((item) => {
            let obj = {};
            obj.itemKey = item.reservationItem;
            obj.itemAmount = "";
            obj.taxAmount = "";
            obj.itemTaxAmount = "";
            obj.taxRate = this.form.taxRate;
            obj.quantity = 1;
            obj.uint = "個";
            obj.unitPrice = "";
            obj.remark = item.remark;
            this.bizInvoiceItemList.push(obj);
          });
        });
      },
      /** 复选框选中數据 */
      SelectionChange(selection) {
        this.checkedList = selection.map((item) => item.index);
      },
      /** 預約事項明細序號 */
      rowItemIndex({ row, rowIndex }) {
        row.index = rowIndex + 1;
      },
      /** 預約事項明細添加按钮操作 */
      add() {
        let obj = {};
        obj.itemKey = "";
        obj.itemAmount = "";
        obj.taxAmount = "";
        obj.itemTaxAmount = "";
        obj.taxRate = this.form.taxRate;
        obj.quantity = 1;
        obj.uint = "個";
        obj.unitPrice = "";
        this.bizInvoiceItemList.push(obj);
      },
      /** 預約事項明細删除按钮操作 */
      del() {
        if (this.checkedList.length == 0) {
          this.$modal.msgError("請先選擇要删除的明細數据");
        } else {
          const bizInvoiceItemList = this.bizInvoiceItemList;
          const checkedList = this.checkedList;
          this.bizInvoiceItemList = bizInvoiceItemList.filter(function (item) {
            return checkedList.indexOf(item.index) == -1;
          });
        }
      },
      // 計算金額
      amountSum(item) {
        this.bizInvoiceItemList[item.index - 1].taxRate = this.form.taxRate;
        this.bizInvoiceItemList[item.index - 1].taxAmount = this.computeTaxAmount(
          this.bizInvoiceItemList[item.index - 1].itemAmount,
          this.form.taxRate
        );
        this.bizInvoiceItemList[item.index - 1].itemTaxAmount =
          this.computeItemTaxAmount(
            this.bizInvoiceItemList[item.index - 1].itemAmount,
            this.form.taxRate
          );
        this.$forceUpdate();
        this.bizInvoiceItemList.splice(1, 0);
      },
      computeTaxAmount(itemAmount, taxRate) {
        return (itemAmount * taxRate).toFixed(2);
      },
      computeItemTaxAmount(itemAmount, taxRate) {
        return (itemAmount * (1 + (taxRate - 0))).toFixed(2);
      },
      // 稅率變化
      taxRate_change() {
        this.bizInvoiceItemList.map((item) => {
          item.taxRate = this.form.taxRate;
          item.taxAmount = this.computeTaxAmount(
            item.itemAmount,
            this.form.taxRate
          );
          item.itemTaxAmount = this.computeItemTaxAmount(
            item.itemAmount,
            this.form.taxRate
          );
        });
        this.$forceUpdate();
        this.bizInvoiceItemList.splice(1, 0);
      },
      // form.taxRate
      /** 提交按钮 */
      submitForm(type) {
        console.log(this.bizInvoiceItemList);
        this.form.taxAmount = 0; //稅金
        this.form.quoteAmount = 0; //報價金額
        this.form.quoteTaxAmount = 0; // 含稅報價
        this.bizInvoiceItemList.map((item) => {
          item.unitPrice = item.itemAmount;
          this.form.quoteAmount += item.itemAmount - 0;
          this.form.taxAmount += item.taxAmount - 0;
          this.form.quoteTaxAmount += item.itemTaxAmount - 0;
        });
        // unitPrice
        // (scope.row.itemAmount * form.taxRate).toFixed(2)
        this.form.bizQuoteItemList = this.bizInvoiceItemList;
        this.form.quoteStatus = type;
        console.log(this.form);
        this.$refs["form"].validate((valid) => {
          if (valid) {
            addQuote(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.$tab.closePage().then(() => {
                // 执行結束的逻辑
                const obj = { path: "/quote/quote", name: "Quote" };
                this.$tab.refreshPage(obj);
              });
            });
          }
        });
      },
      cancel() {
        this.$tab.closePage().then(() => {
          // 执行結束的逻辑
          const obj = { path: "/quote/quote", name: "Quote" };
          this.$tab.refreshPage(obj);
        });
      },
  
      open_dialog() {
        this.open = true;
        this.dialog_if = true;
        this.getList();
      },
      getList() {
        // 根据实际需求，调用对应接口...........
        this.loading = true;
        listBank({
          bankType: "10",
          pageNum: 1,
          pageSize: 9999,
        })
          .then((res) => {
            this.userList = res.rows;
            this.total = res.total;
            this.loading = false;
            //   數据回显
            let that = this;
            this.$nextTick(() => {
              console.log(this.multipleSelection);
              if (this.form.inBankNo && this.form.inBankNo != "") {
                this.userList.forEach((row) => {
                  if (row.id == this.select_customer.id) {
                    that.$refs.multipleTable.toggleRowSelection(row);
                  }
                });
              } else {
                that.$refs.multipleTable.clearSelection();
              }
            });
          })
          .catch((err) => {
            console.log(err);
            this.loading = false;
          });
      },
      choose_bank() {
        // inBankNo
        //           inBankName
        console.log(1111);
        console.log(this.multipleSelection);
  
        this.select_customer = this.multipleSelection[0];
        this.form.inBankNo = this.multipleSelection[0].bankNo;
        this.form.inBankId = this.multipleSelection[0].id;
        this.form.inBankAccount = this.multipleSelection[0].accountName;
        this.form.inBankName = this.multipleSelection[0].bankName;
        this.$refs.multipleTable.clearSelection();
        this.open = false;
        this.dialog_if = false;
      },
      cancel_bank() {
        this.$refs.multipleTable.clearSelection();
        this.open = false;
      },
      handleSelectionChange(val) {
        if (val.length > 1) {
          this.$refs.multipleTable.clearSelection();
          this.$refs.multipleTable.toggleRowSelection(val.pop());
        }
      },
      selectTable(selection, row) {
        this.multipleSelection = [row];
      },
  
      // 選擇客戶
      open_dialog_customer() {
        this.open_customer = true;
        this.dialog_if_customer = true;
        this.getList_customer();
      },
      getList_customer() {
        // 根据实际需求，调用对应接口...........
        this.loading = true;
        listCustomer(this.queryParams)
          .then((res) => {
            this.userList_customer = res.rows;
            this.total = res.total;
            this.loading = false;
            //   數据回显
            let that = this;
            this.$nextTick(() => {
              console.log(this.multipleSelection_customer);
              if (this.form.customerCode && this.form.customerCode != "") {
                this.userList_customer.forEach((row) => {
                  if (row.id == this.select_customer_customer.id) {
                    that.$refs.multipleTable_customer.toggleRowSelection(row);
                  }
                });
              } else {
                that.$refs.multipleTable_customer.clearSelection();
              }
            });
          })
          .catch((err) => {
            console.log(err);
            this.loading = false;
          });
      },
      choose_customer_customer() {
        console.log(1111);
        console.log(this.multipleSelection_customer);
        this.select_customer_customer = this.multipleSelection_customer[0];
  
        this.form.customerCode = this.multipleSelection_customer[0].customerCode;
        this.form.customerId = this.multipleSelection_customer[0].id;
        this.form.customerName = this.multipleSelection_customer[0].customerName;
  
        this.$refs.multipleTable_customer.clearSelection();
        this.open_customer = false;
        this.dialog_if_customer = false;
      },
  
      // 取消按钮
      cancel_customer_customer() {
        this.$refs.multipleTable_customer.clearSelection();
        this.open_customer = false;
      },
      handleSelectionChange_customer(val) {
        if (val.length > 1) {
          this.$refs.multipleTable_customer.clearSelection();
          this.$refs.multipleTable_customer.toggleRowSelection(val.pop());
        }
      },
      selectTable_customer(selection, row) {
        this.multipleSelection_customer = [row];
      },
    },
  };
  </script>
    <style  >
  .signType thead .el-table-column--selection .cell {
    display: none;
  }
  .dialog-footer {
    width: 100%;
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
  </style>
      